﻿using CsvHelper;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;


namespace Compass.Wpf.Extensions;

public static class CommonExtensions
{
    //调用win api将指定名称的打印机设置为默认打印机
    [DllImport("winspool.drv")]
    public static extern bool SetDefaultPrinter(string printerName);

    /// <summary>
    /// 生成二维码
    /// </summary>
    /// <param name="content"></param>
    /// <returns></returns>
    public static Bitmap GetQrCodeBitmap(this string content)
    {
        //QRCodeGenerator ：用来通过指定的方式生成二维码存储的数据对象，
        //也就是 QRCodeData 二维码中间的 Matrix，
        //之后 QRCode 得到 QRCodeData 并生成二维码
        var codeGenerator = new QRCoder.QRCodeGenerator();
        //这里设置容错率的一个级别 QRCoder.QRCodeGenerator.ECCLevel.M
        //版本 1 ~ 40
        var codeData = codeGenerator.CreateQrCode(content, QRCoder.QRCodeGenerator.ECCLevel.M, true, true, QRCoder.QRCodeGenerator.EciMode.Utf8, 5);
        
        var code = new QRCoder.QRCode(codeData);
        return code.GetGraphic(4);





    }

    /// <summary>
    /// 从csv文件读取数据
    /// </summary>
    public static List<T> GetRecords<T>(this string path)
    {
        //数据存储在SliderParam.csv文件中，方便excel编辑
        //https://joshclose.github.io/CsvHelper/getting-started/
        //Install-Package CsvHelper

        //Excel默认以ANSI格式保存csv文件，读取的时候中文会乱码，应当指定Encoding为GB2312
        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
        using var reader = new StreamReader(path, Encoding.GetEncoding("GB2312"));
        using var csv = new CsvReader(reader, CultureInfo.InvariantCulture);
        return csv.GetRecords<T>().ToList();
    }




}